import os
import fnmatch
import re


def search_string_in_files(directory, search_string):
    matches = []

    # Walk through directory and subdirectories
    for root, dirnames, filenames in os.walk(directory):
        for filename in fnmatch.filter(filenames, '*.py'):
            filepath = os.path.join(root, filename)

            with open(filepath, 'r', encoding='utf-8') as file:
                try:
                    content = file.read()
                    for match in re.finditer(search_string, content):
                        # Store the result as a tuple (filepath, line_number, start_pos)
                        line_number = content.count('\n', 0, match.start()) + 1
                        start_pos = match.start()
                        matches.append((filepath, line_number, start_pos))
                except Exception as e:
                    print(f"Could not read file {filepath}: {e}")

    return matches


# Example usage
directory_to_search = r'E:\CODE\unet_pytorch_lc'
search_term = 'SegmentationClass'
results = search_string_in_files(directory_to_search, search_term)

for filepath, line_number, start_pos in results:
    print(f"Found in {filepath} at line {line_number}, position {start_pos}")
